import { getToken, setToken, removeToken } from '@/utils/auth'
import { loginApi, getUserInfo, getMyPermissions } from '@/api/user'
import { constantRoutes, resetRouter } from '@/router'

const state = {
  token: getToken(),
  userInfo: {}, // 当前用户信息
  routes: constantRoutes, // 保存所有的路由信息
  myPermission: [] // 保存当前用户权限
}

const mutations = {
  // 保存token
  setToken(state, token) {
    state.token = token // 只是设置了vuex中的数据
    setToken(token)
  },
  // 清除token
  removeToken(state) {
    state.token = ''
    removeToken()
  },
  // 保存当前用户信息
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  // 设置路由
  setRoutes(state, routes) {
    state.routes = [...constantRoutes, ...routes]
  },
  // 清空路由
  removeRoutes(state) {
    state.routes = constantRoutes
  }
}

const actions = {
  // 登录
  async loginAsync(store, data) {
    const res = await loginApi(data)
    store.commit('setToken', res.data.jwt)
  },
  // 获取用户信息
  async getUserInfoAsync(store) {
    const { data } = await getUserInfo()
    store.commit('setUserInfo', data)
  },
  // 获取当前用户权限
  async getMyPermission(store) {
    const res = await getMyPermissions()
    return res
  },
  // 退出登录
  logout(store) {
    // 清除token
    store.commit('removeToken')
    // 清空用户信息
    store.commit('setUserInfo', {})
    // 清空vuex中的路由
    store.commit('removeRoutes')
    // 重置路由
    resetRouter()
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
